<template>
    <div class="discover-container">

      <!-- 用户信息页面（默认隐藏） -->
    <div v-if="showUserProfile" class="user-profile-view">
      <div class="profile-header">
        <el-button class="back-button" @click="backToMain">
          <el-icon><ArrowLeft /></el-icon> 返回
        </el-button>
      </div>
      <!-- 用户信息展示，复用您的用户页面组件 -->
      <OtherUser :user="currentUser" />
    </div>

    <div v-if="showMainProfile">
      <div  class="tags-container">
        <el-tag
          v-for="tag in tags"
          :key="tag"
          :type="activeTag === tag ? '' : 'info'"
          class="tag-item"
          @click="activeTag = tag"
        >
          {{ tag }}
        </el-tag>
      </div>
      <div class="notes-container">
        <div v-for="note in filteredNotes" :key="note.id" class="note-card" >
          <div class="note-image">
            <img :src="note.image" alt="加载失败" @click="showNoteDetailDialog(note)"/>
          </div>
          <div class="note-content">
            <h3>{{ note.title }}</h3>
            <p>{{ note.description }}
              <el-tag
                  v-for="tag in note.tags"
                  :key="tag"
                  size="small"
                  class="image-tag"
                  style="margin-left: 3px;"
                >
                  {{ tag }}
              </el-tag>
            </p>

             <!-- 新增的用户信息和点赞区域 -->
             <div class="note-footer">
              <div class="user-info" >
                <el-avatar :size="20" :src="note.avatar" @click="showUserProfilePage(note)" />
                <span class="username" @click="showUserProfilePage(note)">{{ note.username }} </span>
                    <div class="like-section">
                    <el-icon 
                      :class="['like-icon', { liked: note.isliked }]" 
                      @click="toggleLike(note)"
                    >
                      <Star />
                    </el-icon>
                    <span class="like-count">{{ note.likes }}</span>
                  </div>
              </div>  
            </div>

          </div>
        </div>
      </div>
    </div>


      <!-- 帖子详情弹窗 -->
    <el-dialog
      v-model="showNoteDetail"
      :fullscreen="isMobile"
      :show-close="false"
      custom-class="note-detail-dialog"
      @close="closeDetail"
    >
      <div class="note-detail-container">
        <!-- 左侧图片区域 - 全屏无间距 -->
        <div class="detail-left">
          <div class="image-container">
            <img :src="currentNote.images[currentImageIndex]" alt="note image" />
            <div v-if="currentNote.images.length > 1" class="side-nav-arrows">
              <div class="nav-arrow left" @click.stop="prevImage">
                <el-icon><ArrowLeft /></el-icon>
              </div>
              <div class="nav-arrow right" @click.stop="nextImage">
                <el-icon><ArrowRight /></el-icon>
              </div>
            </div>
            <div v-if="currentNote.images.length > 1" class="dot-indicators">
              <div
                v-for="(img, index) in currentNote.images"
                :key="index"
                class="dot"
                :class="{ active: currentImageIndex === index }"
                @click.stop="currentImageIndex = index"
              ></div>
            </div>
          </div>
        </div>

        <!-- 右侧内容区域 - 可滚动 -->
        <div class="detail-right">
          <div class="scroll-content">
            <!-- 用户信息区域 -->
            <div class="user-info">
              <el-avatar :size="50" :src="currentNote.avatar" />
              <div class="user-meta">
                <span class="username">{{ currentNote.name }}</span>
                <span class="follow-count">{{ currentNote.followers }} 粉丝</span>
              </div>
              <el-button
                v-if="!currentNote.isFollowing"
                type="danger"
                round
                class="follow-btn"
                @click="followAuthor"
              >
                关注
              </el-button>
              <el-button
                v-else
                type="info"
                round
                class="follow-btn"
                @click="followAuthor"
              >
                已关注
              </el-button>
              <el-button
                type="danger"
                round
                class="follow-btn"
                @click="talk"
              >
                私信
              </el-button>
            </div>

            <el-divider />

            <!-- 帖子内容 -->
            <div class="note-content">
              <h2>{{ currentNote.title }}</h2>
              <p>{{ currentNote.content }}</p>
            </div>

            <el-divider />

            <!-- 评论区 -->
            <div class="comments-section">
              <h3>评论 ({{ currentNote.comments.length }})</h3>
              <div class="comment-list">
                <!-- 遍历嵌套评论 -->
                <template v-for="comment in nestedComments" :key="comment.id"  >
                  <!-- 渲染当前评论 -->
                 <div class="comment-item-xian">
                  

                  <div
                    class="comment-item"
                    :style="{ 'margin-left': comment.depth * 20 + 'px' }"
                  >
                    <el-avatar :size="40" :src="comment.avatar" />
                    <div class="comment-content">
                      <div class="comment-header">
                        <span class="comment-author">{{ comment.username }}</span>
                        <span class="comment-time">{{ formatTime(comment.createtime) }}</span>
                      </div>
                      <p class="comment-text">{{ comment.content }}</p>
                      <div v-if="comment.images" class="comment-images">
                        <img
                          v-for="(img, idx) in comment.images"
                          :key="idx"
                          :src="img"
                          alt="comment image"
                          @click="showImagePreview(img)"
                        />
                      </div>
                      <div class="comment-actions">
                        <span @click="likeComment(comment)">
                          <el-icon :class="['icon', { 'dianzan': comment.isdianzan }]"><Star /></el-icon> {{ comment.likes }}
                        </span>
                        <span @click="replyToComment(comment)">回复</span>
                      </div>
                    </div>
                  </div>

                  <!-- 递归渲染子评论 -->
                  <template v-if="comment.replies && comment.replies.length">
                  <div
                    v-for="reply in comment.replies"
                    :key="reply.id"
                    class="comment-item"
                    :style="{ 'margin-left': reply.depth * 20 + 'px' }"
                  >
                    <el-avatar :size="30" :src="reply.avatar" />
                    <div class="comment-content">
                      <div class="comment-header">
                        <span class="comment-author">{{ reply.username }}</span>
                        <span class="comment-time">{{ formatTime(reply.createtime) }}</span>
                      </div>
                      <p class="comment-text">
                        <template v-if="reply.replyusername">
                          <span class="reply-mention">回复 @{{ reply.replyusername }} : </span>
                        </template>
                        {{ reply.content }}
                      </p>
                      <div v-if="reply.images" class="comment-images">
                        <img
                          v-for="(img, idx) in reply.images"
                          :key="idx"
                          :src="img"
                          alt="comment image"
                          @click="showImagePreview(img)"
                        />
                      </div>
                      <div class="comment-actions">
                        <span @click="likeComment(reply)">
                          <el-icon :class="['icon', { 'dianzan': reply.isdianzan }]"><Star /></el-icon> {{ reply.likes }}
                        </span>
                        <span @click="replyToComment(reply)">回复</span>
                      </div>
                    </div>
                  </div>
                </template>
                </div>
                </template>
              </div>
            </div>
          </div>
          <!-- 固定评论框 -->
          <div class="fixed-comment-input">
            <!-- 回复用户信息显示（当有回复对象时显示） -->
            <div v-if="replyingTo" class="reply-info">
              <span>回复 @{{ replyingTo.username }}</span>
              <el-icon class="close-reply" @click="cancelReply"><Close /></el-icon>
            </div>

            <!-- 正常模式（未聚焦输入框时） -->
            <div v-if="!isInputFocused" class="comment-normal-mode">
              <!-- 左侧输入框 -->
              <el-input
                v-model="newComment"
                placeholder="写下你的评论..."
                class="comment-input"
                @focus="handleInputFocus"
              />
              
              <!-- 右侧操作按钮 -->
              <div class="action-buttons">
                <div class="action-item" @click="toggleLikeNote">
                  <el-icon :class="['icon', { 'liked': currentNote.isliked }]"><Star /></el-icon>
                  <span>{{ currentNote.likes }}</span>
                </div>
                
                <div class="action-item" @click="toggleFavorite">
                  <el-icon :class="['icon', { 'favorited': currentNote.isFavorited }]"><Collection /></el-icon>
                  <span>{{ currentNote.collectioncount }}</span>
                </div>
                
                <div class="action-item" @click="handleInputFocus">
                  <el-icon class="icon"><ChatDotRound /></el-icon>
                  <span>{{ currentNote.comments.length }}</span>
                </div>
                
                <div class="action-item" @click="shareNote">
                  <el-icon class="icon"><Share /></el-icon>
                  <span>分享</span>
                </div>
              </div>
            </div>

            <!-- 编辑模式（聚焦输入框时） -->
            <div v-else class="comment-edit-mode">
              <!-- 文本输入区（可自动扩展高度） -->
              <el-input
                v-model="newComment"
                type="textarea"
                :rows="textAreaRows"
                placeholder="写下你的评论..."
                class="comment-textarea"
                @input="adjustTextareaHeight"
              />
              
              <!-- 底部操作栏 -->
              <div class="edit-actions">
                <!-- 左侧功能按钮 -->
                <div class="left-actions">
                  <el-icon class="action-icon" @click="insertMention"><User /></el-icon>
                  <!-- 表情包预留位置 -->
                  <el-icon class="action-icon" @click="showEmojiPicker"><HelpFilled /></el-icon>
                  <el-icon class="action-icon" @click="showFavoriteEmojis"><Star /></el-icon>
                  <el-icon class="action-icon" @click="uploadImage">
                    <input 
                      type="file" 
                      ref="imageInput" 
                      accept="image/*" 
                      style="display: none" 
                      @change="handleImageUpload"
                    />
                    <Picture />
                  </el-icon>
                </div>
                
                <!-- 右侧操作按钮 -->
                <div class="right-actions">
                  <el-button class="cancel-btn" @click="cancelComment">取消</el-button>
                  <el-button 
                    class="send-btn" 
                    type="danger" 
                    :disabled="!newComment.trim()"
                    @click="submitComment(currentNote)"
                  >
                    发送
                  </el-button>
                </div>
              </div>
            </div>
          </div>

        </div>
      </div>
    </el-dialog>

    <!-- 私信聊天弹窗 -->
<el-dialog
  v-model="showPrivateChat"
  title="私信"
  width="800px"
  :fullscreen="isMobile"
  custom-class="private-chat-dialog"
>
  <div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <el-avatar :size="40" :src="currentChatUser.avatar" />
      <span class="chat-username">{{ currentChatUser.name }}</span>
    </div>
    
    <!-- 聊天内容区域 -->
    <div class="chat-messages">
      <div 
        v-for="message in chatMessages" 
        :key="message.id"
        class="message-item"
        :class="{ 'my-message': message.senderid === currentUserId  }"
      >
        <el-avatar 
          v-if="message.senderid !== currentUserId  "
          :size="36" 
          :src="message.senderAvatar" 
          class="message-avatar"
        />
        
        <div class="message-content">
          <div v-if="message.type === 'text'" class="message-text">
            {{ message.content }}
          </div>
          <img 
            v-else-if="message.type === 'image'" 
            :src="message.content" 
            alt="图片" 
            class="message-image"
          />
          
          <div class="message-time">
            {{ formatTime(message.createdat) }}
          </div>
        </div>
        
        <el-avatar 
          v-if="message.senderid === currentUserId  "
          :size="36" 
          :src="currentUserAvatar" 
          class="message-avatar"
        />
      </div>
    </div>
    
    <!-- 聊天输入区域 -->
    <div class="chat-input-area">
      <!-- 表情选择器 -->
      <div class="emoji-picker">
        <el-popover placement="top-start" width="300" trigger="click">
          <template #reference>
            <el-icon class="emoji-icon"><HelpFilled /></el-icon>
          </template>
          <div class="emoji-grid">
            <span 
              v-for="emoji in ['😀', '😂', '😍', '👍', '❤️', '🙏']" 
              :key="emoji"
              @click="sendEmoji(emoji)"
            >
              {{ emoji }}
            </span>
          </div>
        </el-popover>
      </div>
      
      <!-- 消息输入框 -->
      <el-input
        v-model="newMessage"
        type="textarea"
        :rows="2"
        placeholder="输入消息..."
        class="message-input"
        @keyup.enter="sendMessage"
      />
      
      <!-- 操作按钮 -->
      <div class="chat-actions">
        <el-icon class="action-icon" @click="uploadChatImage">
          <input 
            type="file" 
            ref="chatImageInput" 
            accept="image/*" 
            style="display: none" 
            @change="handleChatImageUpload"
          />
          <Picture />
        </el-icon>
        
        <el-button 
          type="primary" 
          size="small" 
          @click="sendMessage"
          :disabled="!newMessage.trim()"
        >
          发送
        </el-button>
      </div>
    </div>
  </div>
</el-dialog>

    </div>
  </template>

  <script setup>
  import { ref, computed, onMounted, onUnmounted,watch } from 'vue'
  import { Star, ArrowLeft, ArrowRight,HelpFilled } from '@element-plus/icons-vue'
  import { ElForm, ElFormItem, ElInput, ElButton, ElCard,ElMessage  } from 'element-plus';
  import Profile from './Profile.vue'  // 引入Profile组件
  import OtherUser from './OtherUser.vue'
  import request from '../utils/request';
  import { debounce } from 'lodash-es'
  import { useUserStore } from '../utils/userStore'
  import '../assets/css/Discover.css'  // 引入CSS样式
  const userStore = useUserStore()
  // 定义一个定时器变量
let chatRefreshTimer = null;
  
  const tags = ref(['推荐', '穿搭', '美食', '旅行', '美妆', '家居'])
  const activeTag = ref('推荐')
  const showUserProfile = ref(false) //用户页面
  const showMainProfile  = ref(true) //主页面
  const currentUser = ref(null)
  // 评论相关
const isInputFocused = ref(false)
const textAreaRows = ref(1)
const replyingTo = ref(null)
const imageInput = ref(null)

// 2. 创建响应式 users
const users = ref(null)

// 3. 定义获取用户数据的函数
const fetchUsers = () => {
  
  const user = userStore.getUser
  users.value = user
  console.log(users.value)
}

onMounted(async () => {
  
  fetchUsers() //加载当前登录用户信息
  getMainList(); // 加载页面帖子信息
  window.addEventListener('resize', checkMobile)
  checkMobile()
  
})

const currentUserId = computed(() => users.value?.id || null)
const currentUserAvatar = computed(() => users.value?.avatar || null)


onUnmounted(() => {
  // // 移除窗口激活事件监听器
  // window.removeEventListener('focus', loadChatHistory);

  window.removeEventListener('resize', checkMobile)
})

// 当用户登录后状态变化时，重新加载数据
watch(
  () => userStore.getUser, // 监听用户状态变化
  () => {
    // 重新加载数据
    fetchUsers();
    getMainList();
  }
);

  const Form = ref({
    userId: '',
    targettype:'', // 目标类型(1-帖子 2-评论)
    page: '1',
    size: '15'
})

const loading = ref(false)
const notes = ref([])
  const getMainList = async () => {
    try {
      Form.value.userId =users.value.id;
    }catch (error) {
      Form.value.userId ="";
    }
    

    loading.value = true
    try {
      
      const main = await request.post('/xhs/main/getMainList', Form.value)
      
      notes.value = main.data.records.map(note => ({
        ...note,
        tags: parseTags(note.tags) // 确保 tags 是数组
      }));
      
    } catch (error) {
      console.error('请求失败:', error)
      ElMessage.error(`查询失败: ${error.message}`)
    } finally {
      loading.value = false
    }
  }

  const parseTags = (tags) => {
    try {
      if (!tags) return [];
      return typeof tags === 'string' ? JSON.parse(tags) : tags;
    } catch (e) {
      return [];
    }
  };

// 监听标签变化，自动加载数据
watch(fetchUsers,activeTag, getMainList, { immediate: true });

  const filteredNotes = computed(() => {
    if (activeTag.value === '推荐') {
      return notes.value
    }
    return notes.value.filter(note => note.tags.includes(activeTag.value))
  })

  // 帖子点赞，后台修改数据
  const dz_Like = ref({
  id: '', 
  likes: '', 
  userid: '', 
  targettype: 1, //目标类型(1-帖子 2-评论 3-收藏 )
  likes:null,
  isliked:null,
  collectioncount:null,
  talkid:'',
})

// 显示用户信息页面 查询用户信息
const showUserProfilePage = async(author) => {  
  const user = await request.post('/sys/user/getUserId', {"id":author.userid})
  
  currentUser.value = user.data;
 
  showUserProfile.value = true
  showMainProfile.value = false
}

// 返回主页面
const backToMain = () => {
  showUserProfile.value = false
  showMainProfile.value = true
}

const currentImageIndex = ref(0)
const newComment = ref('')
const isMobile = ref(false)

  // 新增状态管理
const showNoteDetail = ref(false)
const currentNote = ref({
  id: null,
  images: [],
  title: '',
  content: '',
  tags: [],
  comments: []
})


// 点开帖子看详情弹窗，展示信息
const showNoteDetailDialog = async (note) => {
  
  // 转换数据格式
  const fatieid = note.userid;  // 发帖人的id
  const userId = users.value.id //当前登录用户的id

  const res = await request.post('/xhs/main/getMainList', {"id":note.id,"targettype":"1","userId":userId,"fatieid":fatieid})
  const main = res.data.records[0];
  const images = parseTags(main.imagesort)
  const talk = await request.post('/xhs/talk/getByContentid', {"contentid":main.id,"targettype":"2","userId":users.value.id})
  currentNote.value = {
    ...main,
    id: main.id,
    //images: [note.image], // 将单图片转为数组
    images: images, // 将单图片转为数组
    name: main.username,
    avatar: main.avatar,
    isFollowing: main.isFollowing === 0 ? false : true,// 是否关注
    followers: main.followers,   // 粉丝数量
    followListId: main.followListId,  // 关注表id
    content: main.description,
    collectioncount:main.collectioncount,
    comments: generateComments(talk)
  }
  currentImageIndex.value = 0
  showNoteDetail.value = true
}

// 生成评论数据结构
const generateComments =  (talk) => {
  
  const comments = []
  for (let i = 0; i < talk.data.length; i++) {
    comments.push({
      id: talk.data[i].id,
      isdianzan: talk.data[i].isdianzan === 0 ? false : true,// 是否点赞
      userid: talk.data[i].userid,
      contentid: talk.data[i].contentid,//
      username:  talk.data[i].username,
      avatar: talk.data[i].avatar,
      content: talk.data[i].content,
      createtime: talk.data[i].createtime,
      likes: talk.data[i].likes,
      depth:talk.data[i].depth,
      parentid:talk.data[i].parentid,
      images: talk.data[i].imageid ? [talk.data[i].imageid] : undefined
    })
  }
  return comments
}

// 计算嵌套评论结构
const nestedComments = computed(() => {
  const comments = currentNote.value.comments || [];
  // 获取一级评论 (depth=0)
  const topLevelComments = comments.filter(c => c.depth === 0);
  // 为每个一级评论添加 replies 属性
  return topLevelComments.map(comment => ({
    ...comment,
    replies: getReplies(comments, comment.id)
  }));
});

// 递归获取子评论
const getReplies = (comments, parentId) => {
  const replies = comments.filter(c => c.parentid === parentId);
  return replies.map(reply => ({
    ...reply,
    replies: getReplies(comments, reply.id) // 递归获取子评论
  }));
};

 // 帖子点赞，后台修改数据
 const followList = ref({
  userid: '', 
  followerid: '', 
  relationtype: '', 
  followername: '',  
  followeravatar:'',
  isliked:null,
  followListId:'',// 关注信息id 
})

// 关注作者
const followAuthor = async() => {
  currentNote.value.isFollowing = !currentNote.value.isFollowing
  followList.value.userid = users.value.id, //当前用户id
  followList.value.followerid = currentNote.value.userid, //当前帖子用户id
  followList.value.relationtype = 1,  // 关系类型(1-普通粉丝,2-铁粉,3-好友,4-拉黑)
  followList.value.followername = currentNote.value.username,
  followList.value.followeravatar = currentNote.value.avatar,
  followList.value.isliked = currentNote.value.isFollowing  //关注或者取消 
  followList.value.followListId = currentNote.value.followListId // 关注信息id,用于删除
  const main = await request.post('/xhs/followinglist/addOrDeletFollow', followList.value)
  
}

 // 主页面点赞/取消点赞
 const toggleLike =  async(note) => {
  const user = userStore.getUser // 获取用户信息
  
  note.isliked = !note.isliked
  note.likes += note.isliked ? 1 : -1
  dz_Like.value.id = note.id,
  dz_Like.value.likes = note.likes
  dz_Like.value.userid = users.value.id  // 当前登录用户id 暂写死 待修改
  dz_Like.value.targettype = 1
  dz_Like.value.isliked = note.isliked
  const main = await request.post('/xhs/main/updateMain', dz_Like.value)
}

// 详情页面 点赞笔记
const toggleLikeNote =async () => {
  
  currentNote.value.isliked = !currentNote.value.isliked
  currentNote.value.likes += currentNote.value.isliked ? 1 : -1

  dz_Like.value.id = currentNote.value.id,
  dz_Like.value.likes = currentNote.value.likes
  dz_Like.value.userid =users.value.id  // 当前登录用户id 暂写死 待修改
  dz_Like.value.targettype = 1
  dz_Like.value.isliked = currentNote.value.isliked
  const main = await request.post('/xhs/main/updateMain', dz_Like.value)
}

// 收藏笔记
const toggleFavorite =async () => {
  currentNote.value.isFavorited = !currentNote.value.isFavorited
  currentNote.value.collectioncount += currentNote.value.isFavorited ? 1 : -1

  dz_Like.value.id = currentNote.value.id,
  dz_Like.value.collectioncount = currentNote.value.collectioncount // 收藏数
  dz_Like.value.userid =users.value.id  //  
  dz_Like.value.targettype = 3   //目标类型(1-帖子 2-评论  3-收藏)
  dz_Like.value.isliked = currentNote.value.isFavorited  //
  const main = await request.post('/xhs/main/updateMain', dz_Like.value)
}

// 评论点赞功能实现
const likeComment = async(comment) => {
      const aa = comment ;
      //findIndex 查找数组中是否有相同 id 的 comment。如果找到（index !== -1），就用新 comment 替换旧的,如果没找到（index === -1），就用 unshift 把新 comment 插入到数组开头。
      comment.isdianzan = !comment.isdianzan
      comment.likes += comment.isdianzan ? 1 : -1

      dz_Like.value.id = comment.contentid,  //帖子id
      dz_Like.value.talkid = comment.id,    // 评论id 
      dz_Like.value.commentcount = comment.likes // 评论数
      dz_Like.value.userid =users.value.id  //  
      dz_Like.value.targettype = 2   //目标类型(1-帖子 2-评论  3-收藏)
      dz_Like.value.isliked = comment.isdianzan  //点赞或取消点赞
      const main = await request.post('/xhs/main/updateMain', dz_Like.value)

      const index = currentNote.value.comments.findIndex(c => c.id === comment.id);
    if (index !== -1) {
      currentNote.value.comments[index] = comment; // 替换匹配到的 comment
    } else {
      currentNote.value.comments.unshift(comment); // 如果没有匹配到，就插入到开头
    }

}


// 提交评论
const submitComment = async (current) => {
  
  if (newComment.value.trim()) {
    const commentData = ref({
      userid: users.value.id, // 当前登录的用户 ID
      content: newComment.value, // 实际的评论内容
      contentid:current.id, // 实际的帖子 ID
      createtime: new Date(),
      usernickname:current.userid, // 实际的发帖人 ID
      likes: 0,
      depth: replyingTo.value ? 1 : 0,
      parentid: replyingTo.value  ? (replyingTo.value.depth === 1 ? replyingTo.value.parentid : replyingTo.value.id) : null,
      replyuserid: replyingTo.value === null ? null: replyingTo.value.userid ,   
      replyusername: replyingTo.value  === null ? null: replyingTo.value.username,
      imageid:''
    })
    const res = await request.post('/xhs/talk/saveTalk', commentData.value)
    currentNote.value.comments = res.data;
    cancelComment()
  }

}

// 回复评论
const replyToComment = (comment) => {
  
  replyingTo.value = {
    id: comment.id, //评论id
    depth: comment.depth, // 是否一级评论，0是，1否
    parentid: comment.parentid, //一级评论id
    userid: comment.userid,
    username: comment.username
  }
  isInputFocused.value = true
}

// 取消回复
const cancelReply = () => {
  replyingTo.value = null
}

// 取消评论
const cancelComment = () => {
  isInputFocused.value = false
  newComment.value = ''
  replyingTo.value = null
  textAreaRows.value = 1
}

// 分享笔记
const shareNote = () => {
  // 分享功能实现
  console.log('分享笔记')
}

// 插入@提及
const insertMention = () => {
  newComment.value += '@'
}

// 显示表情选择器
const showEmojiPicker = () => {
  // 显示表情选择器逻辑
  console.log('显示表情选择器')
}

// 显示收藏表情
const showFavoriteEmojis = () => {
  // 显示收藏表情逻辑
  console.log('显示收藏表情')
}

// 上传图片
const uploadImage = () => {
  imageInput.value.click()
}

// 处理图片上传
const handleImageUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    // 处理图片上传逻辑
    console.log('上传图片:', file.name)
  }
}

const prevImage = () => {
  currentImageIndex.value = (currentImageIndex.value - 1 + currentNote.value.images.length) % currentNote.value.images.length
}

const nextImage = () => {
  currentImageIndex.value = (currentImageIndex.value + 1) % currentNote.value.images.length
}

const formatTime = (time) => {
  // 时间格式化
  return new Date(time).toLocaleString()
}

const closeDetail = () => {
  showNoteDetail.value = false
}

const checkMobile = () => {
  isMobile.value = window.innerWidth < 768
}



// 处理输入框聚焦
const handleInputFocus = () => {
  isInputFocused.value = true
}

// 调整文本框高度
const adjustTextareaHeight = () => {
  const lineCount = (newComment.value.match(/\n/g) || []).length + 1
  textAreaRows.value = Math.min(Math.max(lineCount, 1), 4)
}


// 私信相关状态 ==================================================================================
const showPrivateChat = ref(false)
const currentChatUser = ref(null)
const chatMessages = ref([])
const newMessage = ref('')
const chatImageInput = ref(null)

const addMessage = () => {
  // 正确访问内部数组并使用 push 方法
  chatMessages.value.push('新消息');
};

// 打开私信对话框
const talk = async () => {
  // 设置当前聊天用户
  currentChatUser.value = {
    id: currentNote.value.userid,
    name: currentNote.value.name,
    avatar: currentNote.value.avatar
  }
  // // 监听窗口激活事件
  // window.addEventListener('focus', loadChatHistory);
  // 加载历史消息
  await loadChatHistory()
  chatRefreshTimer = setInterval(() => {
        loadChatHistory();
      }, 3000);
  
  showPrivateChat.value = true
  //showNoteDetail.value = false // 关闭帖子详情
}

// 加载聊天历史
const loadChatHistory = async () => {
  try {
    const response = await request.post('/xhs/messages/getMessages', {
      senderid: users.value.id,
      receiverid: currentChatUser.value.id
    })
    chatMessages.value = response.data.data;
  } catch (error) {
    ElMessage.error('加载聊天记录失败')
  }
}

// 监听聊天窗口的显示状态
watch(showPrivateChat, (newVal) => {
  if (!newVal) {
    // 如果聊天窗口关闭，清除定时器
    clearInterval(chatRefreshTimer);
  }
});

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim()) return
  
  try {
    const messageData = {
      senderid: users.value.id,
      receiverid: currentChatUser.value.id,
      content: newMessage.value,
      type: 'text' // text/image/emoji
    }
    
    const res = await request.post('/xhs/messages/sendMessage', messageData)
    
     // 确保 chatMessages.value 是数组
     if (!Array.isArray(chatMessages.value)) {
      chatMessages.value = []
    }

    // 添加到本地消息列表
    chatMessages.value.push({
      ...messageData,
      id: res.data.data.id,
      createdat: new Date().toISOString(),
      senderavatar: users.value.avatar,
      sendername: users.value.username
    })
    
    newMessage.value = ''
    // 发送消息后重新加载聊天历史
    //await loadChatHistory();
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败')
  }
}

// 上传聊天图片
const uploadChatImage = () => {
  chatImageInput.value.click()
}

// 处理聊天图片上传
const handleChatImageUpload = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  try {
    const formData = new FormData()
    formData.append('image', file)
    formData.append('senderId', users.value.id)
    formData.append('receiverId', currentChatUser.value.id)
    
    const res = await request.post('/xhs/chat/uploadImage', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    // 添加到本地消息列表
    chatMessages.value.push({
      id: res.data.id,
      senderId: users.value.id,
      receiverId: currentChatUser.value.id,
      content: res.data.imageUrl,
      type: 'image',
      createdat: new Date().toISOString(),
      senderavatar: users.value.avatar,
      sendername: users.value.username
    })
    
  } catch (error) {
    console.error('图片上传失败:', error)
    ElMessage.error('图片上传失败')
  }
}

// 发送表情
const sendEmoji = (emoji) => {
  newMessage.value += emoji
}

// 私信相关状态 ==================================================================================

  </script>
  
  <style scoped>
  
  /* 在CSS部分添加以下样式 */
.private-chat-dialog {
  border-radius: 12px;
  overflow: hidden;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 500px;
}

.chat-header {
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  gap: 10px;
}

.chat-username {
  font-weight: bold;
}

.chat-messages {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
  gap: 10px;
  align-items: flex-start;
}

.my-message {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
}

.message-text {
  padding: 10px 14px;
  background-color: #f5f5f5;
  border-radius: 18px;
  word-break: break-word;
}

.my-message .message-text {
  background-color: #409eff;
  color: white;
}

.message-image {
  max-width: 200px;
  max-height: 200px;
  border-radius: 8px;
}

.message-time {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: center;
}

.chat-input-area {
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.emoji-picker {
  display: flex;
}

.emoji-icon {
  font-size: 20px;
  cursor: pointer;
  color: #666;
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 8px;
  font-size: 20px;
  cursor: pointer;
}

.message-input {
  flex: 1;
}

.chat-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.action-icon {
  font-size: 20px;
  cursor: pointer;
  color: #666;
  margin-right: 10px;
}
  </style>